package com.ybkj.daijia.api.util;

import com.ybkj.daijia.server.Constant;
import com.ybkj.daijia.serverUtils.IOUtils;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Base64;
import javax.imageio.ImageIO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

/**
 * Created by Administrator on 2017/2/6.
 */
@SuppressWarnings("restriction")
@Slf4j
public class ImageUtil {


    // 1MB
    public static float MB = 1048576;
    private static final double RATE_REDUCTION = 0.5;

    @SneakyThrows
    public static void main(String[] args) {
        String fullPath = "G:\\gitlab\\daijia\\server\\src\\main\\webappupload/driver\\24150c98f0934df6bd4c0c4b386e56ee.jpg";
        String s = IOUtils.readFileToBase64(fullPath);
        String newPath = "D:\\321322198511205873F.jpg";
        String s1 = useGoogleZoom(s, 1f);
        byte[] decode = Base64.getDecoder().decode(s1);
        FileOutputStream fileOutputStream = new FileOutputStream(newPath);
        fileOutputStream.write(decode);
        fileOutputStream.close();
/*
 实现1: 4M图片压缩得太小了, 只有0.3M, 如果要求不要压得这么小, 那做不到
 long length = new File(fullPath).length();
        // 如果图片大于等于0.5MB 则按80%缩小
        if (length / MB >= 0.5) {
            try {
                ImageUtil.zoom(fullPath, newPath, 2);
            } catch (IOException e) {
                log.error("出错啦:" + e);
            }
        }
        String base64Str = IOUtils.readFileToBase64(newPath);
        System.out.println("base64Str===" + base64Str);*/

    }

    /***
     * 检查图片的base64是否超过指定大小范围
     * @param base64 图片的base64编码
     * @param maxMbSize 指定的mb大小
     * @return
     */
    public static boolean checkImageBase64Size(String base64, float maxMbSize) {
        int length = base64.length();
        if (base64.startsWith("data:image/png;base64,")) {
            length -= "data:image/png;base64,".length();
        }
        float mbSize = length / ImageUtil.MB;
        return mbSize > maxMbSize;
    }

    public static String checkSizeAndConvertToBase64(String path, float maxMbSize) {
        FileInputStream fis;
        ByteArrayOutputStream out = null;
        byte[] data = null;
        try {
            fis = new FileInputStream(path);
            data = new byte[fis.available()];
            fis.read(data);
            if (data.length / MB > maxMbSize) {
                out = useGoogleZoom(data, maxMbSize);
                data = out.toByteArray();
            }
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("压缩错误", e);
            }
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                if (log.isErrorEnabled()) {
                    log.error("关闭流错误", e);
                }
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }

    /***
     * 调用google thumbnails 压缩图片, 该方法会仅可能的保留图片的质量, 像素不变
     * 4.30M的图片要求2M以内循环压缩了两次,最后1.94M 大小合适
     * @param base64 要压缩得base64图片字符串
     * @param maxMbSize 要求图片最多多大, 单位MB
     * @return 压缩后的图片的base64编码
     * @throws IOException
     */
    public static String useGoogleZoom(String base64, float maxMbSize) {
        byte[] decode = Base64.getDecoder().decode(base64);
        ByteArrayOutputStream out = null;
        try {
            out = useGoogleZoom(decode, maxMbSize);
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("压缩错误", e);
            }
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                if (log.isErrorEnabled()) {
                    log.error("关闭流错误", e);
                }
            }
        }
        return Base64.getEncoder().encodeToString(out.toByteArray());
    }

    /**
     * 调用google thumbnails 压缩图片, 该方法会仅可能的保留图片的质量, 像素不变 4.30M的图片要求2M以内循环压缩了两次,最后1.94M 大小合适
     *
     * @param data        数组
     * @param maxMbSize 要求图片最多多大, 单位MB
     * @return
     * @throws IOException
     */
    public static ByteArrayOutputStream useGoogleZoom(byte[] data, float maxMbSize) throws IOException {
        DecimalFormat df = Constant.DECIMAL_ZERO;
        float quality = 0.995f;
        float reduction = 0.003f;
        int i = 1;
        float newFileLength = 0f;
        float oldSize = data.length / MB;
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        float minus = oldSize - maxMbSize;
        log.info("原始图片大小：" + df.format(oldSize) + "MB");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        boolean isReset = false;
        do {
            if (newFileLength > 0f && !isReset) {
                in.close();
                in = new ByteArrayInputStream(out.toByteArray());
                out.reset();
            }else if(isReset) {
                in.close();
                in = new ByteArrayInputStream(data);
                out.reset();
            }
            quality = quality - reduction * (i - 1);
            if (log.isInfoEnabled()) {
                log.info("{} qualiy = {}", i, quality);
            }
            Thumbnails.of(in).scale(1f).outputQuality(quality).outputFormat("jpg").toOutputStream(out);
            newFileLength = out.toByteArray().length / MB;
            if (newFileLength > oldSize) {
                isReset = true;
                quality -= 0.2f;
                if (log.isInfoEnabled()) {
                    log.info("反压缩了, quality重新设置");
                }
                reduction = 0.03f;
                continue;
            }
            float per = (oldSize - newFileLength) / minus;
            if (per > 0) {
                float v = 1 / per;
            }
            if (log.isInfoEnabled()) {
                log.info("压缩次数：{}, 压缩后图片大小：{}", i, newFileLength);
            }
            i++;
        } while (newFileLength >= maxMbSize);
        return out;
    }

    /**
     * 调用google thumbnails 压缩图片, 该方法会仅可能的保留图片的质量, 像素不变 4.30M的图片要求2M以内循环压缩了两次,最后1.94M 大小合适
     *
     * @param srcFilePath 需要压缩得图片位置
     * @param newFilePath 新文件的地址
     * @param maxMbSize   要求图片最多多大, 单位MB
     * @return
     * @throws IOException
     */
    public static void useGoogleZoom(String srcFilePath, String newFilePath, float maxMbSize) {
        // 设置保留位数
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(newFilePath);
            in = new FileInputStream(srcFilePath);
            byte[] data = new byte[in.available()];
            in.read(data);
            ByteArrayOutputStream zoom = useGoogleZoom(data, maxMbSize);
            out.write(zoom.toByteArray());
        } catch (FileNotFoundException e) {
            if (log.isErrorEnabled()) {
                log.error("文件打开错误", e);
            }
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("压缩错误", e);
            }
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                if (log.isErrorEnabled()) {
                    log.error("关闭流错误", e);
                }
            }
        }
        // 调整方向
        if (log.isInfoEnabled()) {
            log.info("新文件的路径:{}", newFilePath);
        }
    }


    public static ByteArrayOutputStream zoom(InputStream in, double maxMbSize) throws IOException {
        // 设置保留位数
        DecimalFormat df = Constant.DECIMAL_ZERO;
        double rate = 0.9999;
        log.info("原始图片大小：" + df.format((float) in.available() / MB) + "MB");
        int i = 1;
        double newFileLength = 0.0;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 如果首次压缩还大于2MB则继续处理
        do {
            // 暂定按照0.03频率压缩
            rate = rate - RATE_REDUCTION * (i - 1);
            if (log.isInfoEnabled()) {
                log.info("{} rate= {}", i, rate);
            }
            BufferedImage srcImage = ImageIO.read(in);
            int width = (int) (srcImage.getWidth() * rate);
            int height = (int) (srcImage.getHeight() * rate);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.drawImage(srcImage, 0, 0, width, height, null);
            // 缩小
            ImageIO.write(image, "jpg", out);
            newFileLength = out.toByteArray().length / MB;
            if (log.isInfoEnabled()) {
                log.info("压缩次数：{}, 压缩后图片大小：{}", i, newFileLength);
            }
            i++;
        } while ((float) newFileLength >= maxMbSize);
        return out;
    }


    /**
     * 压缩图片
     *
     * @param srcFilePath 源文件路径
     * @param newFilePath 新文件路径
     * @param maxMbSize   允许压缩后最大的MB值
     * @throws IOException
     */
    public static void zoom(String srcFilePath, String newFilePath, double maxMbSize) throws IOException {
        // 设置保留位数
        FileInputStream in = new FileInputStream(srcFilePath);
        ByteArrayOutputStream zoom = zoom(in, maxMbSize);
        FileOutputStream out = new FileOutputStream(newFilePath);
        out.write(zoom.toByteArray());
        // 调整方向
        if (log.isInfoEnabled()) {
            log.info("新文件的路径:{}", newFilePath);
        }
    }

    /**
     * 对图片进行旋转
     *
     * @param src   被旋转图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static BufferedImage Rotate(Image src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // 计算旋转后图片的尺寸
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        // 进行转换
        g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        g2.drawImage(src, null, null);
        return res;
    }

    /**
     * 计算旋转后的图片
     *
     * @param src   被旋转的图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // 如果旋转的角度大于90度做相应的转换
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }

}

